package com.lvan.fileupload.service.impl;

import com.lvan.fileupload.bean.ResultMsg;
import com.lvan.fileupload.service.FileService;
import com.lvan.fileupload.utils.ZipUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.lvan.fileupload.utils.ConstantJarPath.*;

/**
 * @author Lvan
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String singleFileUpload(MultipartFile file) {
        BufferedOutputStream stream = null;
        String filePath = "";
        try {
            // 获取文件新路径使用UUID，防止文件重名
            String fileName = getNewFilePath(file);
            filePath = FILE_DIR + fileName;
            File upFile = new File(ABSOLUTE_PATH, STATIC_DIR + filePath);
            if (!upFile.getParentFile().exists()) {
                upFile.getParentFile().mkdirs();
            }
            // 创建字节缓冲输出流
            stream = new BufferedOutputStream(new FileOutputStream(upFile));
            stream.write(file.getBytes());
            stream.flush();
            stream.close();
            return filePath;
        } catch (IOException e) {
            try {
                e.printStackTrace();
                assert stream != null;
                stream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return "";
        }
    }

    @Override
    public List<String> batchFileUpload(MultipartFile[] files) {
        List<String> pathList = new ArrayList<>();
        ResultMsg resultMsg = null;
        for (MultipartFile file : files) {
            if (!file.isEmpty()) {
                String path = singleFileUpload(file);
                if (StringUtils.isEmpty(path)) {
                    break;
                } else {
                    pathList.add(path);
                }
            }
        }
        return pathList;
    }

    @Override
    public String singleFileDownload(String fileName, HttpServletResponse response) {
        FileInputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            File file = new File(ABSOLUTE_PATH, STATIC_DIR + FILE_DIR + fileName);
            if (!file.exists()) {
                return "文件不存在";
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            byte[] buff = new byte[1024];
            int i = 0;
            while ((i = inputStream.read(buff)) != -1) {
                outputStream.write(buff, 0, i);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
            return "";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return "文件名转码错误";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "文件不存在";
        } catch (IOException e) {
            e.printStackTrace();
            try {
                assert outputStream != null;
                outputStream.close();
                inputStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return "文件下载错误";
        }
    }

    @Override
    public String batchFileDownload(String[] fileName, HttpServletResponse response) {
//        createDirIfNotExists();
        try {
            // 创建临时文件夹
            String downPath = ABSOLUTE_PATH + STATIC_DIR + FILE_DIR + "downzip/";
            File file = new File(downPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 将需要下载文件复制到临时文件夹
            for (String f : fileName) {
                String uploadPath = ABSOLUTE_PATH + "/" + STATIC_DIR + FILE_DIR + f;
                ZipUtils.copyFile(uploadPath, downPath + f);
            }
            // 设置response,设置压缩包名称
//            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("批量下载.zip", "utf-8"));
            // 下载zip
            ZipUtils.toZip(downPath, response.getOutputStream(), true);
            // 删除临时文件夹
            File[] listFiles = file.listFiles();
            for (int i = 0; i < listFiles.length; i++) {
                listFiles[i].delete();
            }
            file.delete();
            return "";
        } catch (IOException e) {
            e.printStackTrace();
            return "批量下载失败";
        }
    }

    private String getNewFilePath(MultipartFile file) {
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 新文件名，使用UUID防止文件重名
        return uuid + suffixName;
    }
}
